<template>
  <a-card :bordered="false">
    <!-- <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="关键字">
              <a-select
                placeholder="请选择类别"
                v-model="queryParam.type"
              >
                <a-select-option :value="1">通知通告</a-select-option>
                <a-select-option :value="2">材料示范</a-select-option>
                <a-select-option :value="3">评审结果</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 8px" @click="setEmpty">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div> -->

    <div v-if="!$store.getters.isMzRole" class="table-operator">
      <span style="margin-right: 16px;">已选中{{ selectedRowKeys.length }}行</span>
      <a-button type="primary" icon="plus" @click="handleAdd">新增</a-button>
      <a-button icon="delete" @click="handleDeleteBatch">删除</a-button>
    </div>

    <s-table
      ref="table"
      size="default"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data="loadData"
      :rowSelection="rowSelection"
      showPagination="auto"
    >
      <span slot="serial" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>
      <span slot="reportTitle" slot-scope="text">
        <ellipsis :length="20" tooltip>{{ text }}</ellipsis>
      </span>
      <span slot="type" slot-scope="text">
        {{ text | typeFilter }}
      </span>
      <span slot="notificationFileList" slot-scope="text">
        <div :key="item.id" v-for="item in text">
          <!-- <a :href="item.url" target="_black" :download="item.original">{{ item.original }}</a> -->
          <a @click="$fileDownLoad(item)">{{ item.original }}</a>
        </div>
      </span>
      <span slot="image" slot-scope="text, record">
        <img :src=" text?.url" alt="" class="reportImg" @click="preview(record)">
      </span>

      <span slot="action" slot-scope="text, record">
        <template>
          <a @click="handleCheck(record)">查看</a>
          <a-divider type="vertical" />
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleDelete(record)">删除</a>
        </template>
      </span>
    </s-table>

    <a-modal :visible="previewVisible" :footer="null" @cancel="()=>previewVisible = false">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
    <create-form
      ref="createModal"
      :visible="visible"
      :loading="confirmLoading"
      :model="mdl"
      @cancel="handleCancel"
      @ok="handleOk"
    />
    <check-form
      ref="checkModal"
    />
  </a-card>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import { getReport, saveReport, deleteReport } from '@/api/report'

import CreateForm from './CreateForm'
import CheckForm from './CheckForm'

let columns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '类别',
    dataIndex: 'type',
    scopedSlots: { customRender: 'type' }
  },
  {
    title: '标题',
    dataIndex: 'title',
    scopedSlots: { customRender: 'reportTitle' }
  },
  {
    title: '发布日期',
    dataIndex: 'pushDate'
  },
  {
    title: '附件',
    dataIndex: 'notificationFileList',
    scopedSlots: { customRender: 'notificationFileList' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'NoticeReport',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    CheckForm
  },
  data () {
    // 民政角色不展示操作项
    if (this.$store.getters.isMzRole) {
      columns = columns.filter(v => v.dataIndex != 'action')
    }
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 查询参数
      queryParam: {
        type: 3
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log('loadData request parameters:', requestParameters)
        return getReport(requestParameters)
          .then(res => {
            console.log(res)
            return res
          })
      },
      selectedRowKeys: [],
      selectedRows: [],
      previewVisible: false,
      previewImage: ''
    }
  },
  created () {
  },
  filters: {
    typeFilter (type) {
      const typeMap = {
        1: '通知通告',
        2: '材料示范',
        3: '评审结果'
      }
      return typeMap[type]
    }
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    setEmpty () {
      this.queryParam = { type: 3 }
      this.$refs.table.refresh(true)
    },
    handleDeleteBatch () {
      if (this.selectedRowKeys.length === 0) {
        this.$warning({
          title: '提示',
          content: '请选择需要删除的数据'
        })
      } else {
        console.log(this.selectedRowKeys)
        deleteReport({
            id: this.selectedRowKeys.join(',')
          }).then(res => {
              // 刷新表格
              this.$refs.table.refresh()
              this.$message.success('批量删除成功')
            })
      }
    },
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    handleEdit (record) {
      let annexList = []
      if (record.notificationFileList) {
        annexList = record.notificationFileList.map(item => {
          const { id, original, url } = item
          return {
            uid: id,
            name: original,
            status: 'done',
            url: url
          }
        })
      }
      let imageList = []
      if (record.image) {
        const { id, original, url } = record.image
        imageList = [{
          uid: id,
          name: original,
          status: 'done',
          url: url
        }]
      }
      let detailList = []
      if (record.detail) {
        const { id, original, url } = record.detail
        detailList = [{
          uid: id,
          name: original,
          status: 'done',
          url: url
        }]
      }
      this.mdl = { ...record, annexList, imageList, detailList }
      this.visible = true
      // 为了解决编辑之后弹框消失，再次打开弹框时候wangeditor报错
      // 原因是wangeditor没有被销毁，所以标签上加上 v-if="visible"
      // 但是如果不先让this.visible = true，让弹框显示，在赋值mdl，那么 v-decorator会报错
      // setTimeout(() => {
      //   this.mdl = { ...record, annexList, imageList, detailList }
      // }, 0)
    },
    handleCheck (record) {
      this.$refs.checkModal.checkView(record)
    },
    handleDelete (record) {
      this.$confirm({
        title: '删除确认',
        content: '确认要删除该数据吗？并且不可恢复！',
        okType: 'danger',
        onOk: () => {
          deleteReport({
            id: record.id
          }).then(res => {
              // 刷新表格
              this.$refs.table.refresh()
              this.$message.success('删除成功')
            })
        }
      })
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          values.imageId = values.imageList && values.imageList.length > 0 ? values.imageList[0].uid : ''
          delete values.imageList
          values.fileIdList = values.annexList && values.annexList.length > 0 ? values.annexList.map(item => item.uid) : []
          delete values.annexList
          values.detailId = values.detailList && values.detailList.length > 0 ? values.detailList[0].uid : ''
          delete values.detailList
          values.type = 3
          saveReport(values).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success(values.id > 0 ? '修改成功' : '新增成功')
            }).finally(() => {
              this.confirmLoading = false
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    preview (record) {
      this.previewImage = record.image?.url
      this.previewVisible = true
    }
  }
}
</script>

<style lang="less" scoped>
.reportImg {
  display: block;
  height: 36px;
  cursor: pointer;
}
</style>
